package com.idcloud.common.utils;

import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回类
 */
@Data
public class R<T> {

    private int code = 200;

    private String msg = "请求成功";

    private T data;

    public R() {

    }

    public R(T data) {
        if(data == null){
            this.data = (T) new HashMap<>();
        }
        else{
            if (data.getClass().equals(Query.class)) {
                Map<String, Object> map = new HashMap<>();
                map.put("list", ((Query) data).getRecords());
                map.put("total", ((Query) data).getTotal());
                this.data = (T) map;
            } else {
                this.data = data;
            }
        }
    }

    public R(Throwable e) {
        super();
        this.code = 500;
        if (e != null) {
            this.msg = e.getMessage();
        } else {
            this.msg = "数据为空";
        }
        this.data = (T) new HashMap<>();
    }

    public void setRCode(int code){
        this.code=code;
        if(code==200){
            this.msg = "请求成功";
        }
        if(code==201){
            this.msg = "数据已存在";
        }
        if(code==300){
            this.msg = "数据为空";
        }
        if(code==401){
            this.msg = "认证失败";
        }
        if(code==402){
            this.msg = "token过期";
        }
        if(code==403){
            this.msg = "权限不足";
        }
        if(code==500){
            this.msg = "服务器错误";
        }
        this.data = (T) new HashMap<>();
    }
}
